const { join } = require('path');
const fs = require('then-fs');

// 拼接文件路径
const filename = join(__dirname, 'db.json');

// ------------------ 获取数据 ----------------------
async function query() {
    let data = await fs.readFile(filename, 'utf-8');
    return JSON.parse(data);
}

// ------------------ 添加数据 ----------------------
async function add(row) {
    let res = await query();
    let id = res[res.length - 1].id + 1;
    row.id = id;
    res.push(row);
    return fs.writeFile(filename, JSON.stringify(res));
}

// ------------------ 删除数据 ----------------------
async function del(id) {
    //id = "14";
    let res = await query();
    let result = res.filter(item => item.id != id);
    //console.log(id)
    return fs.writeFile(filename, JSON.stringify(result));
}

// ------------------ 修改数据 ----------------------
async function update(row) {
    let res = await query();
    let index = res.findIndex(item => item.id == row.id);
    res.splice(index, 1, row);
    return fs.writeFile(filename, JSON.stringify(res));
}

// ------------------ 查询数据 ----------------------

//根据ID给出具体信息
async function search_id(id) {
    let res = await query();//拿到所有数组
    let data = res.filter(item => item.id == id);//查出需要的数组
    console.log(data[0])//控制台监视
    return data[0];//输出
}

// ------------------ 查询数据 ----------------------

//根据给出的作者，给出该作者的所有书籍
async function user(author) {
    let res = await query();//拿到所有数组
    let data = res.filter(item => item.author == author);//查出需要的数组
    return data;//输出
}




// 导出
module.exports = { query, add, del, update, search_id, user };

